package cn.tedu.store.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.tedu.store.controller.ex.FileEmptyException;
import cn.tedu.store.controller.ex.FileSizeException;
import cn.tedu.store.controller.ex.FileTypeException;
import cn.tedu.store.controller.ex.FileUploadIOException;
import cn.tedu.store.entity.User;
import cn.tedu.store.service.IUserService;
import cn.tedu.store.util.ResponseResult;
/**
 * 处理用户相关请求的控制器类
 * @author Administrator
 *
 */
@RestController
@RequestMapping("users")
public class UserController extends BaseController {

	@Autowired
	private IUserService userService;

	@PostMapping("reg")
	public ResponseResult<Void> reg(User user){
		//执行注册
		userService.reg(user);//异常在父类中统一处理了，这里不用处理
		//ResponseResult类用来返回给客户端的信息 state=1
		return new ResponseResult<>(SUCCESS);
	}

	@PostMapping("login")
	public ResponseResult<User> login(String username,String password,HttpSession session){
		//执行登录，获取返回值
		User data = userService.login(username, password);
		//将uid和username保存到session中
		session.setAttribute("uid", data.getUid());
		session.setAttribute("username", data.getUsername());
		//响应成功，失败都回去找异常处理
		return new ResponseResult<>(SUCCESS, data);
	}

	@PostMapping("change_password")
	public ResponseResult<Void> changePassword(
			@RequestParam("old_password") String oldPassword,
			@RequestParam("new_password") String newPassword,
			HttpSession session){
		//从Session中获取当前登录的用户的uid
		Integer uid = getUidFromSession(session);

		userService.changePassword(uid, oldPassword, newPassword);
		return new ResponseResult<>(SUCCESS);
	}

	@GetMapping("info")
	public ResponseResult<User> getByUid(HttpSession session){
		//从Session中获取uid
		Integer uid = getUidFromSession(session);
		//执行查询
		User data = userService.getByUid(uid);
		//返回成功与查询结果
		return new ResponseResult<>(SUCCESS, data);
	}

	@PostMapping("change_info")
	public ResponseResult<Void> changeInfo(User user,HttpSession session){
		//从Session中获取uid
		Integer uid = getUidFromSession(session);
		//将uid封装到user中，因为用户填的信息中没有uid，uid登录后设置在Session中
		user.setUid(uid);
		userService.changeInfo(user);
		return new ResponseResult<>(SUCCESS);
	}

	/**
	 * 上传头像
	 */
	//设置上传头像的内存最大值为1M
	private static final long UPLOAD_MAX_SIZE=1*1024*1024;
	//允许上传的头像的文件类型列表
	private static final List<String> UPLOAD_CONTENT_TYPES=new ArrayList<>();
	static {
		UPLOAD_CONTENT_TYPES.add("image/jpeg");
		UPLOAD_CONTENT_TYPES.add("image/bmp");
		UPLOAD_CONTENT_TYPES.add("image/png");
		UPLOAD_CONTENT_TYPES.add("image/gif");
	}

	@PostMapping("change_avatar")
	public ResponseResult<String> changeAvatar(
			//SpringBoot框架要求上传文件必须加这个注解
			@RequestParam("avatar") MultipartFile avatar, 
			HttpSession session) {
		// 检查上传文件是否为空
		if(avatar.isEmpty()) {
			throw new FileEmptyException("请选择需要上传的文件！");
		}
		// 检查文件大小
		long size = avatar.getSize();
		if (size > UPLOAD_MAX_SIZE) {
			throw new FileSizeException(
					"上传头像失败！文件大小不超过1M");
		}
		// 检查文件类型
		String contentType = avatar.getContentType();
		if(!UPLOAD_CONTENT_TYPES.contains(contentType)) {
			throw new FileTypeException("文件类型支持！允许上传的类型有：" + UPLOAD_CONTENT_TYPES);
		}


		// 基于session获取上传文件夹的路径
		String parentPath = session.getServletContext().getRealPath("upload");
		// 检查上传文件夹是否存在，如果不存在，则创建
		File parent = new File(parentPath);
		if (!parent.exists()) {
			parent.mkdirs();
		}

		// 通过参数avatar获取原始文件名
		String originalFilename = avatar.getOriginalFilename();
		// 获取文件的扩展名
		int beginIndex = originalFilename.lastIndexOf(".");
		String suffix = originalFilename.substring(beginIndex);
		// 生成目标文件名
		String filename = UUID.randomUUID().toString() + suffix;

		// 执行保存头像文件
		File dest = new File(parent, filename);
		try {
			avatar.transferTo(dest);
		}catch (IOException e) {
			e.printStackTrace();
			throw new FileUploadIOException("上传头像失败！网络错误！");
		}

		// 执行将头像路径存储到数据库中："/upload/" + 目标文件名
		// http://localhost:8080/upload/1.jpg
		Integer uid = getUidFromSession(session);
		String avatarPath = "/upload/" + filename;
		userService.changeAvatar(uid, avatarPath);

		// 返回成功及头像上传完成所在的路径
		return new ResponseResult<>(SUCCESS, avatarPath);
	}

}
